package com.easydisk.user.handler;

import com.alibaba.fastjson.JSON;
import com.easydisk.response.ApiResponse;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 35536
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ApiResponse<String> handleException(Exception e) {
        return ApiResponse.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Object> returnMethodArgumentNotValid(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        return ApiResponse.fail(getFirstErrorMsg(result));
    }

    public Map<String, String> getErrors(BindingResult result) {
        Map<String, String> map = new HashMap<>();
        List<FieldError> errorList = result.getFieldErrors();
        for (FieldError ff : errorList) {
            // 错误所对应的属性字段名
            String field = ff.getField();
            // 错误的信息
            String msg = ff.getDefaultMessage();
            map.put(field, msg);
        }
        return map;
    }

    /**
     * 返回第一条错误信息
     * @param result
     * @return
     */
    public String getFirstErrorMsg(BindingResult result) {
        List<FieldError> errorList = result.getFieldErrors();
        String res = "未知异常,请求错误";
        if (CollectionUtils.isNotEmpty(errorList)) {
            res =   errorList.get(0).getDefaultMessage();
        }
        return res;
    }
}
